<!--
 * @Author: 李小晴 2689279066@qq.com
 * @Date: 2023-02-08 15:32:28
 * @LastEditors: 李小晴 2689279066@qq.com
 * @LastEditTime: 2023-10-29 10:48:00
 * @FilePath: \zhmc_pc\sys\src\views\Asset\Pasture\Enclosure\components\components\Transfer.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="ts">
import { Form } from '@/components/Form'
import { reactive, ref, watch } from 'vue'
import { ContentWrap } from '@/components/ContentWrap'
import File from '../../../Components/File.vue'
import { zcPastureListAdminApi } from '@/api/fa/pasture'
import { ucDeptListApi } from '@/api/uc/dept'
// import { sysRelFileBatchAddApi } from '@/api/fa/insurance'
import { ucOrgDeptUserListApi } from '@/api/fa/user'
import { useCache } from '@/hooks/web/useCache'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useForm } from '@/hooks/web/useForm'
import { useTable } from '@/hooks/web/useTableTest'

const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// const myDeptList: any = wsCache.get('myDeptList')
// const myUserList: any = ref(wsCache.get('myUserList'))
import { zcAssetListApi } from '@/api/fa/earcon'
import { sysDictRelsApi } from '@/api/dict'
import { required } from '@/utils/formRules'
import { TableLxq } from '@/components/Lxq'
import { zcInsuranceOrderSeeApi } from '@/api/fa/insurance'

const dictRelsData = ref() // 联动数据
const breedSubData = ref([]) // 品种的枚举
// 获取联动关系
const getDictRels = async () => {
  const res = await sysDictRelsApi({
    p_type: 'breed',
    c_type: 'breed_sub'
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    dictRelsData.value = res.data
  }
}

// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

const rules = reactive({
  pasture_org_id: [required],
  pasture_dept_id: [required],
  pasture_user_id: [required],
  insurance_type: [required],
  breed: [required],
  breed_sub: [required],
  amount: [required],
  pasture_dept_name: [required],
  number: [required],
  loan_no: [required]
})

const props = defineProps({
  id: {
    type: String,
    default: null
  },
  currentRow: {
    type: Object,
    default: () => null
  }
})
const loading = ref({
  tree: false,
  save: false
})
// const fileList = ref<UploadUserFile[]>([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const actionType = ref('')

const getInsureSee = async () => {
  if (props.id) {
    const res = await zcInsuranceOrderSeeApi({ id: props.id })
      .catch(() => {})
      .finally(() => {})
    if (res) {
      data.value = await res.data

      // 明细信息处理一下，加上d_id
      await methodsForm.setValues(data.value)
      const json = JSON.parse(data.value.select_json)
      Search.value = {
        breed: json.breed ? json.breed : '',
        breed_sub: json.breed_sub ? json.breed_sub : '',
        earcon_code: json.earcon_code ? json.earcon_code : '',
        asset_code: json.asset_code ? json.asset_code : ''
      }
      console.log(props.id, data.value, '11111')
    }
  } else {
    data.value.state = '1'
    data.value.selected = []
    await methodsForm.setValues(data.value)
  }
}

// 根据畜别查询品种
const breedGetSub = async (breed_value) => {
  console.log(breed_value, 'breed_value')
  if (!breed_value) {
    breedSubData.value = []
  } else {
    let breedData = dictRelsData.value.find((item) => {
      return item.value == breed_value
    })
    breedSubData.value = breedData.children
  }
}

// 选择畜别的时候触发，处理品种类容
const breedChange = async (value) => {
  data.value.checkedAll = false
  data.value.selectData = []
  data.value.noSelectData = []
  // await getList()
  data.value.breed = value
  data.value.breed_sub = ''
  await breedGetSub(value)
  let formData = await methodsForm.getFormData()
  // await methodsForm.setValues(data.value)
  await methodsForm.setValues({ ...formData, breed_sub: '' })
  // await getListAsset()
}

const data = ref<any>({})
data.value.checkedAll = null
data.value.selectData = null
data.value.noSelectData = null
const newDeptTreeData = ref<any[]>([])
const newUserData = ref<any[]>([])

const Search = ref({
  breed: '',
  breed_sub: '',
  asset_code: '',
  asset_code_2: '',
  earcon_code: ''
})

const getListAssetSelect = async () => {
  // data.value.checkedAll = false
  // data.value.selectData = []
  // data.value.noSelectData = []
  // console.log(Search, '差点就')
  await getList()
}
const getListAssetReste = async () => {
  Search.value = {
    breed: '',
    breed_sub: '',
    asset_code: '',
    asset_code_2: '',
    earcon_code: ''
  }
  // await getListAsset()

  await getList()
}
const onCustomer = async (value) => {
  data.value.checkedAll = false
  data.value.selectData = []
  data.value.noSelectData = []
  if (value != data.value.pasture_org_id) {
    data.value.pasture_org_id = value
    newDeptTreeData.value = []
    data.value.pasture_dept_id = ''
    data.value.pasture_dept_name = ''
    await DeptList(value)
    // await getListAsset()
  }
  await methodsForm.setValues(data.value)
  await getList()
}
const onClearCustomer = async () => {
  // data.value.pasture_org_id = ''
  data.value.pasture_dept_id = ''
  data.value.pasture_user_id = ''
}

const DeptList = async (value) => {
  const res = await ucDeptListApi({ org_id: value })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    newDeptTreeData.value = res.data
  }
}

const UserList = async (value) => {
  data.value.pasture_dept_id = value
  newUserData.value = []
  const res = await ucOrgDeptUserListApi({ org_id: data.value.pasture_org_id, dept_id: value })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    newUserData.value = res.data
  }
}

const stateChangeUser = async (value) => {
  data.value.pasture_user_id = value
}

// const stateChangeAdminUser = async (value) => {
//   data.value.admin_user_id = value
// }

// const stateChange = async (value) => {
//   data.value.insurance_type = value
// }

const schema = reactive<FormSchema[]>([
  {
    field: 'pasture_org_id',
    label: '所属牧场',
    component: 'DialogRefer',
    componentProps: {
      getListApi: zcPastureListAdminApi,
      response: { count: 'count', data: 'data' },
      title: '选择牧场（双击选择）',
      nameField: 'pasture_org_name',
      relNameField: 'org_name',
      valueField: 'org_id',
      crudSchemas: [{ field: 'org_name', label: '牧场名称', search: { show: true } }],
      modelName: data.value.pasture_org_name,
      onChange: onCustomer,
      onClear: onClearCustomer
    }
  },
  {
    field: 'pasture_dept_id',
    label: '所属部门',
    component: 'TreeSelect',
    componentProps: {
      data: newDeptTreeData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'dept_id',
      props: {
        children: 'children',
        label: 'dept_name'
      },
      onChange: UserList
    }
  },
  {
    field: 'pasture_user_id',
    label: '所属用户',
    component: 'TreeSelect',
    componentProps: {
      data: newUserData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'user_id',
      props: {
        children: 'children',
        label: 'nickname'
      },
      onChange: stateChangeUser
    }
  },
  // {
  //   field: 'insurance_type',
  //   label: '保险类型',
  //   component: 'Select',
  //   componentProps: {
  //     options: dict.insurance_type,
  //     onChange: stateChange
  //   }
  // },
  {
    field: 'number',
    component: 'Input',
    label: '投保资产数',
    componentProps: {
      disabled: true
    }
  },
  // {
  //   field: 'amount',
  //   component: 'Input',
  //   label: '投保金额'
  // },
  {
    field: 'note',
    component: 'Input',
    label: '备注'
  }
])

const {
  register: registerForm,
  methods: methodsForm,
  elFormRef
} = useForm({
  schema
})

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'asset_code',
    label: '注射编号',
    width: 220,
    search: {
      show: true
    }
  },
  {
    field: 'asset_code_2',
    label: '项圈编号',
    width: 220,
    search: {
      show: true
    }
  },
  {
    field: 'earcon_code',
    label: '耳标编号',
    width: 220,
    search: {
      show: true
    }
  },
  {
    field: 'breed',
    label: '畜别',
    width: 80,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed', cellValue)
    }
  },
  {
    field: 'breed_sub',
    label: '品种',
    width: 120,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed_sub', cellValue)
    }
  },
  {
    field: 'sex',
    label: '性别',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('animal_sex', cellValue)
    }
  },
  {
    field: 'purpose',
    label: '用途',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('purpose', cellValue)
    }
  }
])

const getFormData = async () => {
  let formData = await methodsForm.getFormData()
  // const sku = unref(skuRef)
  // let skuData = sku?.getData()
  // const file = unref(fileRef) //附件
  // let fileData = file?.getData()
  // console.log(fileData, '附件')
  // const goodsDetails = unref(goodsDetailsRef) //明细
  // let goods_details = goodsDetails?.getData()
  // let goods_tag = getGoodsTag()
  // let goods_details = data.value.goods_details
  // let goods_carousel = data.value.goods_carousel
  return { ...formData, selected: data.value.selected }
}

const getListAsset = async (a) => {
  // tableObject.tableList = []
  console.log(tableObject.paramsObj, 'date')
  // if (data.value.pasture_org_id) {
  // getList()
  return zcAssetListApi({
    ...a,
    is_die: '0',
    is_insure: '0',
    pasture_org_id: data.value.pasture_org_id,
    breed: Search.value.breed ? Search.value.breed : null,
    breed_sub: Search.value.breed_sub ? Search.value.breed_sub : null,
    earcon_code: Search.value.earcon_code ? Search.value.earcon_code : null,
    asset_code: Search.value.asset_code ? Search.value.asset_code : null,
    asset_code_2: Search.value.asset_code_2 ? Search.value.asset_code_2 : null
  })
}

const { allSchemas } = useCrudSchemas(crudSchemas)

const { register, tableObject, methods, elTableRef } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: getListAsset,
  response: {
    data: 'data',
    count: 'count'
  }
})
const { getList } = methods

watch(
  () => data,
  (value) => {
    if (!value) return
    methodsForm.setValues(data.value)
  },
  {
    deep: true,
    immediate: true
  }
)

watch(
  () => tableObject.tableList,
  (value) => {
    console.log('tableObject')
    if (!value) return
    if (data.value.checkedAll) {
      setTimeout(() => {
        if (data.value.noSelectData.length > 0) {
          // 去重
          console.log(tableObject.tableList, 'tableObject.tableList')
          console.log('有没有未被选中的')
          let newArr = tableObject.tableList.filter(
            (x) => !data.value.noSelectData.some((item) => x.id == item.id)
          )
          newArr.forEach((row) => {
            elTableRef.value?.toggleRowSelection(row, true)
          })
          console.log(newArr, 'newArr')
        } else {
          tableObject.tableList.forEach((row) => {
            elTableRef.value?.toggleRowSelection(row, true)
          })
        }
      }, 0)
    } else {
      if (data.value.selectData && data.value.selectData.length > 0) {
        data.value.selectData.forEach((row) => {
          elTableRef.value?.toggleRowSelection(row, true)
        })
      } else {
        data.value.selectData = []
      }
    }
  },
  {
    deep: true,
    immediate: true
  }
)

const getRowKey = (row) => {
  return row.id
}

const init = async () => {
  await getDictRels()
  await getInsureSee()
  if (props.currentRow) {
    console.log(props.currentRow, 'props')
    data.value.pasture_org_id = props.currentRow.pasture_org_id
      ? props.currentRow.pasture_org_id
      : ''
    data.value.checkedAll = JSON.parse(props.currentRow.select_json).checkedAll
    data.value.breed = JSON.parse(props.currentRow.select_json).breed
    data.value.breed_sub = JSON.parse(props.currentRow.select_json).breed_sub
    data.value.asset_code = JSON.parse(props.currentRow.select_json).asset_code
    data.value.earcon_code = JSON.parse(props.currentRow.select_json).earcon_code
    await getList()
    if (data.value.breed) {
      await breedGetSub(data.value.breed)
    }
    if (data.value.checkedAll) {
      const aaa: any = []
      JSON.parse(props.currentRow.select_json).selected.forEach((element) => {
        let obj: any = {}
        obj.id = element
        aaa.push(obj)
      })
      data.value.noSelectData = data.value.noSelectData != undefined ? data.value.noSelectData : aaa
    } else if (props.currentRow.select_json) {
      const aaa: any = []
      if (JSON.parse(props.currentRow.select_json).selected) {
        JSON.parse(props.currentRow.select_json).selected.forEach((element) => {
          let obj: any = {}
          obj.id = element
          aaa.push(obj)
        })
      }
      data.value.selectData = aaa
      console.log(data.value.selectData, 'data.value.selectData', aaa)
    }
    if (props.currentRow.pasture_org_id) {
      await DeptList(props.currentRow.pasture_org_id)
    }
    if (props.currentRow.pasture_dept_id) {
      await UserList(props.currentRow.pasture_dept_id)
    }
    //
  } else {
  }
  // }, 0)
}
init()

const save = async (type: string) => {
  switch (type) {
    // case 'selectFile':
    //   const selectFile = unref(selectFileRef)
    //   loading.value.save = true
    //   newFileList.value = await selectFile?.selectData

    //   let res = await sysRelFileBatchAddApi({
    //     source: 'insurance_order',
    //     source_id: props.currentRow.id,
    //     file_ids: newFileList.value.map((element) => element.id)
    //   })
    //     .catch(() => {})
    //     .finally(() => {})
    //   // if (res) {
    //   //   await getSeeFile()
    //   // }

    //   loading.value.save = false
    //   dialogVisible.value = false
    //   break
    default:
      console.log('未知类型')
  }
}

defineExpose({
  methods: methods,
  data,
  getFormData,
  elFormRef,
  Search
})
</script>

<template>
  <ContentWrap title="主数据">
    <Form :rules="rules" @register="registerForm" :data="data" />
  </ContentWrap>

  <ContentWrap title="选择资产">
    <div>
      <el-form :inline="true" :model="Search" class="demo-form-inline">
        <el-form-item label="注射编号">
          <el-input v-model="Search.asset_code" />
        </el-form-item>
        <el-form-item label="项圈编号">
          <el-input v-model="Search.asset_code_2" />
        </el-form-item>
        <el-form-item label="耳标编号">
          <el-input v-model="Search.earcon_code" />
        </el-form-item>
        <el-form-item label="畜别">
          <el-select v-model="Search.breed" placeholder="请选择" clearable @change="breedChange">
            <el-option
              v-for="item in dictRelsData"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="品种">
          <el-select v-model="Search.breed_sub" placeholder="请选择" clearable>
            <el-option
              v-for="item in breedSubData"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getListAssetSelect">查询</el-button>
          <el-button type="" @click="getListAssetReste">重置</el-button>
        </el-form-item>
      </el-form>
      <TableLxq
        v-model:pageSize="tableObject.pageSize"
        v-model:currentPage="tableObject.currentPage"
        v-model:checkedAll="data.checkedAll"
        v-model:noSelectData="data.noSelectData"
        v-model:selectData="data.selectData"
        v-model:total="tableObject.count"
        v-model:tableLen="data.number"
        :columns="allSchemas.tableColumns"
        :data="tableObject.tableList"
        :loading="tableObject.loading"
        :border="true"
        :pagination="{
          total: tableObject.count
        }"
        :row-key="getRowKey"
        :selection="true"
        highlight-current-row
        @register="register"
      />
    </div>
  </ContentWrap>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <File v-if="actionType == 'selectFile'" ref="selectFileRef" :id="Number(data.pasture_org_id)" />
    <template #footer>
      <ElButton type="primary" :loading="loading.save" @click="save(actionType)"> 保存 </ElButton>
      <ElButton @click="dialogVisible = false">关闭</ElButton>
    </template>
  </Dialog>
</template>
